package org.worthydots.access.jpa.dao;

import java.util.List;

import javax.persistence.Query;

import org.worthydots.access.jpa.entity.StationRoute;

public class StationRouteDAOImpl extends DAOImpl implements StationRouteDAO {

	public StationRouteDAOImpl() {
		super();
	}

	public void saveStationRoute(StationRoute stationRoute) {
		entityManager.getTransaction().begin();
		entityManager.merge(stationRoute);
		entityManager.getTransaction().commit();
	}

	public void saveStationRouteIfNotPresent(StationRoute stationRoute) {
		StationRoute stationRouteInDB = getStationRouteByStationRouteId(stationRoute.getId());
		if (stationRouteInDB == null)
			saveStationRoute(stationRoute);
	}

	public StationRoute getStationRouteByStationRouteId(int stationRouteId) {
		return entityManager.find(StationRoute.class, stationRouteId);
	}

	@SuppressWarnings("unchecked")
	public StationRoute getStationRouteByTrainNumberAndStationCode(String trainNumber, String stationCode) {
		Query query = entityManager.createQuery("SELECT sr FROM StationRoute sr WHERE sr.trainNumber = :trainNumber and sr.stationCode = :stationCode");
		query.setParameter("trainNumber", trainNumber);
		query.setParameter("stationCode", stationCode);
		List<StationRoute> resultList = query.getResultList();
		if (resultList != null && resultList.size() == 1)
			return resultList.get(0);
		else if (resultList != null && resultList.size() > 1)
			System.err.println("*** more than 1 row with trainNumber: " + trainNumber + " stationCode: " + stationCode + " ***");

		return null;
	}

	public List<StationRoute> getAllStationRoutes() {
		// TODO Auto-generated method stub
		return null;
	}

	public List<StationRoute> getStationRoutesOfStation(String stationCode) {
		// TODO Auto-generated method stub
		return null;
	}

	public List<StationRoute> getStationRoutesOfTrain(String trainNumber) {
		// TODO Auto-generated method stub
		return null;
	}
}
